﻿using System;
using Csla;
using Csla.Serialization;
using BizControl.DalLinq;
using BizControl.Resources;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.BusinessObjects.Models;
using System.Linq;
using BizControl.Library.Security;

namespace BizControl.Library.BusinessObjects.Marks
{
  [Serializable()]
  public class MarkPeople : BusinessListBase<MarkPeople, PersonMarkLinkBO>
  {
    #region  Business Methods

    private PersonMarkBO _mark;
    
    public PersonMarkLinkBO this[Guid? personMarkIdFor]
    {
      get
      {
        if (personMarkIdFor == null || personMarkIdFor == Guid.Empty) return null;
        foreach (PersonMarkLinkBO personMark in this)
        {
          if (personMark.Person.Id == personMarkIdFor)
            return personMark;
        }
        return null;
      }
    }

    public void AddPerson(PersonBO person)
    {
      if (!(Contains(person.PersonId)))
      {
        PersonMarkLinkBO personMark = PersonMarkLinkBO.NewPersonMarkLink(person, _mark);
        this.Add(personMark);
      }
      else
      {
        throw new InvalidOperationException(ExceptionsMessages.PersonAlreadyHasThisMark);
      }
    }

    public void Remove(Guid personId)
    {
      foreach (PersonMarkLinkBO personMark in this)
      {
        if (personMark.Person.Id == personId)
        {
          Remove(personMark);
          break;
        }
      }
    }

    public bool Contains(Guid personId)
    {
      foreach (PersonMarkLinkBO personMark in this)
        if (personMark.Person.Id == personId)
          return true;
      return false;
    }

    public bool ContainsDeleted(Guid personId)
    {
      foreach (PersonMarkLinkBO personMark in DeletedList)
        if (personMark.Person.Id == personId)
          return true;
      return false;
    }

    #endregion

    #region  Factory Methods

    internal static MarkPeople NewMarkPeople(PersonMarkBO mark)
    {
      return DataPortal.CreateChild<MarkPeople>(mark);
    }

    internal static MarkPeople GetMarkPeople(PersonMark[] data, PersonMarkBO mark)
    {
      return DataPortal.FetchChild<MarkPeople>(data, mark);
    }

    private MarkPeople()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void Child_Create(PersonMarkBO mark)
    {
      if (mark == null) throw new ArgumentNullException(ExceptionsMessages.MarkNullReference);
      _mark = mark;
    }

    private void Child_Fetch(PersonMark[] data, PersonMarkBO mark)
    {
      if (mark == null) throw new ArgumentNullException(ExceptionsMessages.MarkNullReference);
      _mark = mark;
      if (data == null) return;
      this.RaiseListChangedEvents = false;
      foreach (var child in data)
        Add(PersonMarkLinkBO.GetPersonMarkLink(child, _mark));
      this.RaiseListChangedEvents = true;
    }

    #endregion
  }
}